package com.myz.rabbitmq.simple;


import com.myz.rabbitmq.utils.ConnectionUtils;
import com.rabbitmq.client.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 消息消费者
 *
 * @author maoyz on 18-4-4.
 */
public class SimpleRabbitCustomer {
    private static final Logger logger = LoggerFactory.getLogger(SimpleRabbitCustomer.class);
    private final static String QUEUE_NAME = "rabbitMQ.test";

    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = ConnectionUtils.getConnection();
        //4 创建一个通道
        Channel channel = connection.createChannel();
        // 每一次只能消费1个消息
        channel.basicQos(1);
        //5 队列声明queueDeclare
        channel.queueDeclare(QUEUE_NAME, true, false, false, null);

        logger.debug("Customer Waiting Received messages...");

        //6 告诉服务器我们需要那个频道的消息，如果频道中有消息，就会执行回调函数handleDelivery
        //DefaultConsumer类实现了Consumer接口，通过传入一个频道，
        final Consumer consumer = new DefaultConsumer(channel) {
            // 传送
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope,
                                       AMQP.BasicProperties properties, byte[] body)
                    throws IOException {
                String message = new String(body, "UTF-8");
                logger.debug("Customer Received '" + message + "'");
            }
        };
        //7 自动回复队列应答 -- RabbitMQ中的消息确认机制
        channel.basicConsume(QUEUE_NAME, true, consumer);
    }
}
